
import React from "react";
import { Button, Collapse, Popconfirm } from "antd";
import { List } from "antd";
import Controller from "Controller";
import { Element } from "components/Three";
import styles from './index.module.less';
import { IObject3DMap } from "components/Three/interface/IElement";

const { Panel } = Collapse;

export default function ObjectList() {
    return (
        <Collapse ghost defaultActiveKey={['1', '2', '3']} >
            <Panel header="灯光" key="1">
                <ListMain type="light" />
            </Panel>
            <Panel header="模型" key="2">
                <ListMain type="gltf" />
            </Panel>
            <Panel header="标记" key="3">
                <ListMain type="tag" />
            </Panel>
        </Collapse>
    )
}

function ListMain(props: { type: keyof IObject3DMap }) {

    const { type } = props;

    const threeController = Controller.instance.useMemo(s => s.threeController, [])

    const delementMap = threeController.useMemo(s => s.elementMap, [])

    const selectedElementUuid = threeController.useMemo(s => s.selectedElementUuid, []);

    const getName = React.useCallback((item: Element) => item.name, [])

    const className = React.useCallback((item: Element, selectedElementUuid?: string) => item.uuid === selectedElementUuid && styles.no, [])

    const onClick = React.useCallback((e: Element) => threeController.run(async s => s.selectedElementUuid = e.uuid), [threeController])

    const list = React.useMemo(() => {
        const sum = new Array<Element>();
        delementMap.forEach(e => {
            if (e.type === type) {
                sum.push(e);
            }
        })
        return sum;
    }, [delementMap, type])

    const renderDelButton = React.useCallback((item: Element) => {
        return (
            <Popconfirm
                title="警告"
                description="你确定要删除这个对象?"
                onConfirm={() => { threeController.sceneRem(item) }}
            >
                <Button type="text" >删除</Button>
            </Popconfirm>
        )
    }, [threeController])

    return (
        <List
            size="small"
            itemLayout="horizontal"
            dataSource={list}
            renderItem={item => (
                <List.Item
                    className={className(item, selectedElementUuid)}
                    onClick={() => { onClick(item) }}
                    actions={[renderDelButton(item)]}
                >
                    <List.Item.Meta
                        className={`${styles.meta}`}
                        description={<div title={getName(item)} >{getName(item)}</div>}
                    />
                </List.Item>
            )}
        />
    )
}
